<template>
  <div class="app-container">
    <!-- 移除搜索和重置按钮 -->

    <el-row :gutter="10" class="mb8">
      <!-- 保留 "展开/折叠" 按钮 -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
    </el-row>

    <!-- 使用 el-tree 替换 el-table -->
    <el-tree v-if="refreshTable" v-loading="loading" :data="regionList" node-key="code"
      :default-expand-all="isExpandAll" :props="defaultProps">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.name }}</span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import { listRegion } from "@/api/user/region";

export default {
  name: "Region",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 地区信息表格数据
      regionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 树形组件的默认属性配置
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询地区信息列表 */
    getList() {
      this.loading = true;
      listRegion(this.queryParams).then(response => {
        this.regionList = this.handleTree(response.data, "code", "parentCode");
        this.loading = false;
      });
    },
    /** 转换地区信息数据结构 */
    handleTree(data, idKey, parentIdKey) {
      const treeData = [];
      const childMap = {};

      data.forEach(item => {
        if (!childMap[item[idKey]]) {
          childMap[item[idKey]] = { ...item, children: [] };
        } else {
          Object.assign(childMap[item[idKey]], item);
        }
      });

      data.forEach(item => {
        const parent = childMap[item[parentIdKey]];
        if (parent) {
          parent.children.push(childMap[item[idKey]]);
        } else {
          treeData.push(childMap[item[idKey]]);
        }
      });

      return treeData;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        parentCode: null,
        name: null,
        level: null,
        createTime: null,
        updateTime: null,
        isDeleted: null
      };
      this.resetForm("form");
    },
    /** 导出按钮操作 */
    handleExport() {
      // 实现导出逻辑
      console.log('导出功能暂未实现');
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    }
  }
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>